package mybatis;

import mybatis.mapper.UserMapper;
import mybatis.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;

public class MyBatisDemo {

    private static final Logger log = LoggerFactory.getLogger(MyBatisDemo.class);

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-mybatis.xml");
        insert(context);
    }

    /**
     * 编程式事务
     */
    public static void insert(ApplicationContext context) {
        TransactionTemplate transactionTemplate = context.getBean("transactionTemplate",TransactionTemplate.class);
        UserMapper mapper = context.getBean("userMapper",UserMapper.class);
        transactionTemplate.execute(txStatus -> {
            int num = mapper.insert("333");
            //故意报异常测试事务
            int a = 1/0;
            log.info("新增数量：{}", num);
            return null;
        });


    }


    public static void selectList(ApplicationContext context) {
        UserMapper mapper = context.getBean("userMapper",UserMapper.class);
        List<User> users = mapper.selectList();
        for (User user : users) {
            log.info("查询结果： {}", user);
        }
    }
}


